require 'active_record'
require 'active_support'

$db_config = {
        :adapter => "sqlite3",
        :dbfile => "../../bin/dq9d.db"
}

ActiveRecord::Base.establish_connection($db_config)

class Item < ActiveRecord::Base
end

class Alchemy < ActiveRecord::Base
end

def find_item_by_name(name)
  items = Item.find(:all, :conditions=>"`japaness_name` like \"#{name}\"")
  unless items.empty?
    items.each do |item|
      return item if item.japaness_name == name
    end
  end
  raise "item #{name} not found"
end

def find_item_id(name)
  item = find_item_by_name(name)
  return item.id
end

def parse_material(str)
  if str == ""
    return {:material=>0, :num=>0}
  end
    
  strs = str.split("(")
  material_name = strs[0]
  material_id = find_item_id(material_name)
  material_count = strs[1].delete(")").to_i
  return {:material=>material_id, :num=>material_count}
end

def parse(strs)
  product = find_item_id(strs[0]).to_i
  strs.size.upto 4 do |i|
    strs << ""
  end
  materials = []
  1.upto strs.size-1 do |i|
    materials << parse_material(strs[i])
  end
  return {:product=>product, :materials=>materials}
end

def save_alchemy(datas)
  alchemy = Alchemy.find(:first, :conditions=>"product=#{datas[:product]}")
  alchemy_is_nil = alchemy.nil?
  if alchemy_is_nil
    alchemy = Alchemy.new
  end
  alchemy.product = datas[:product]
  alchemy.material1 = datas[:materials][0][:material]
  alchemy.num1 = datas[:materials][0][:num]
  alchemy.material2 = datas[:materials][1][:material]
  alchemy.num2 = datas[:materials][1][:num]
  alchemy.material3 = datas[:materials][2][:material]
  alchemy.num3 = datas[:materials][2][:num]
  alchemy.save
  
  #show log
  product_name = Item.find(alchemy.product).japaness_name
  if alchemy_is_nil
    puts "insert alchemies with alchemy_id=#{alchemy.id}, product=#{product_name}"
  else
    puts "update alchemies with alchemy_id=#{alchemy.id}, product=#{product_name}"
  end
end

sqls = []
File.open("templates/Alchemy.txt", 'r') do |file|
  while line = file.gets
    line.chop!
    strs = line.split("\t")
    begin
      datas = parse(strs)
      save_alchemy(datas)
    rescue Exception=>e
      puts e
    end
  end
end
